#!/usr/bin/python3
# -*- coding: utf-8 -*-

from coreweb import get, post
from datetime import datetime
from sqlalchemy import text, or_, func

import aiohttp_jinja2
import db
import re, hashlib
_RE_EMAIL = re.compile(
    r'^[a-z0-9\.\-\_]+\@[a-z0-9\-\_]+(\.[a-z0-9\-\_]+){1,4}$')
_RE_SHA1 = re.compile(r'^[0-9a-f]{40}$')

# @aiohttp_jinja2.template('index.html')
@get('/', 'index.html')
async def index(*, request):
    session = db.create_session()
    result = [user for user in session.query(db.User)]
    # return {"users": result}
    # return {'user': result[0]}
    summary = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
    result = [
        db.Blog(id=1, user_id=1, user_name='user01', user_image='#', name='blog01',
                summary=summary, content='', created_at=datetime.now(), updated_at=datetime.now())
    ]
    data = {"blogs": result}
    return data
# /favicon.ico转发到静态资源
@get('/favicon.ico')
async def favicon():
    return 'redirect:/static/favicon.ico'

@get('/login', 'login.html')
async def login(request):
    return {}
@get('/logout', 'index.html')
async def logout(request):
    request.__user__ = None
    return 'redirect:/'

@get('/register', 'register.html')
async def register(request):
    return {}
 
@post('/register')
async def do_register(*, email, name, password, request):
    if not name or not name.strip():
        return {'code': -1, 'field': 'name', 'msg': 'name is null'}
    if not email or not _RE_EMAIL.match(email):
        return {'code': -1, 'field': 'email', 'msg': 'email 格式不正确'}
    if not password or not _RE_SHA1.match(password):
        return {'code': -1, 'field': 'password', 'msg': '密码格式不正确'}
    session = db.create_session()
    user = session.query(db.User).filter_by(email=email).first()
    if user:
        return {'code': -1, 'field': 'email', 'msg': '邮箱已注册'}
    user = db.User(name=name, password=password, email=email, admin=False)
    session.add(user)
    session.commit()
    request.__user__ = user
    data = {'code': 0, 'msg': '注册成功'}
    return data

@post('/login')
async def do_login(*, name, password, request):
    if not name or not name.strip():
         return {'code': -1, 'field': 'name', 'msg': '请输入帐号'}
    session = db.create_session()
    user = session.query(db.User).filter(or_(db.User.name==name, db.User.email==name)).first()
    if not user:
        return {'code': -1, 'field': 'name', 'msg': '请输入正确的帐号'}
    print('%s\n%s' % (user.password, hashlib.sha1(('%s:%s' % (user.email, password)).encode('utf-8')).hexdigest()))
    if user.password != hashlib.sha1(('%s:%s' % (user.email, password)).encode('utf-8')).hexdigest():
        return {'code': -1, 'field': 'password', 'msg': '请输入正确的密码'}
    request.__user__ = user
    return {'code': 0, 'msg': '登陆成功'}